//
//  AppDelegate.swift
//  01_新浪微博
//
//  Created by 黄蓉 on 15/12/12.
//  Copyright © 2015年 黄蓉. All rights reserved.
//

import UIKit
import AFNetworking
/// 全局变量记录用户的账号信息,只需要加载一次就可,后续的Token就可以不去磁盘加载了,
///执行的实际,是在需要的时候才会去执行,
///全局变量必须放在@UIApplicationMain上面
let notification = "NSNotification"
let account = UserAccount.loadAccount()
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        ///初始化window
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        ///设置windows的背景颜色
        window?.backgroundColor = UIColor.whiteColor()
        ///设置window的跟控制器
        window?.rootViewController = defaultViewController()
        ///设置window可见并且为主window
        window?.makeKeyAndVisible()
        setupAppearance()
        setupNetWorking()
        //注册通知
        registerNotification()
        return true
    }
    //MARK: -是否显示新版本页面
    private func isNewVersion() -> (Bool) {
        //获取当前版本号
        let infoVersion = NSBundle.mainBundle().infoDictionary!["CFBundleVersion"] as! String
        let currentVersion = Double(infoVersion)
        //获取之前存储的版本号
        //偏好设置
        let ud = NSUserDefaults.standardUserDefaults()
        //读出之前储存的版本号
        let lastVersion = ud.doubleForKey("version")
        //将新的版本号存入
        ud.setValue(currentVersion, forKey: "version")
        //立即写入
        ud.synchronize()
        return currentVersion > lastVersion
        
    }
    
    //MARK: -注册通知
   private func registerNotification() {
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "choseRootVC:", name: notification, object: nil)

    }
    //注销通知,在appdelegate注销没什么区别,编程习惯
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
// MARK: -通知的回调方法
    @objc private func choseRootVC(n: NSNotification) {
        if n.object != nil {
            window?.rootViewController = WelcomeViewController()
        }
        
         window?.rootViewController =  MainViewController()
    }
    
    //判断用户有没有登录
    private func defaultViewController() -> UIViewController {
        //如果用户登录了,判断是否是新版本,来显示不同的控制器
        if UserAccountModel().userLogin {
            
          return  isNewVersion() ? NewFeafureViewController() : WelcomeViewController()
        }
        
        //用户没有登录,返回访客视图
        return MainViewController()
    }
    
    ///设置网络指示器
    private func setupNetWorking() {

        AFNetworkActivityIndicatorManager.sharedManager().enabled = true
        //设置缓存
        let cache = NSURLCache(memoryCapacity: 1024 * 1024 * 2, diskCapacity: 1024 * 1024 * 4, diskPath: nil)
        NSURLCache.setSharedURLCache(cache)
    }
     ///设置全局外观
    private func setupAppearance() {
       
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
 
    }
    
    
    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

